<template>
  <div class="app-container">
    <!-- 新增的查询表单 -->
    <el-form :model="queryForm" ref="queryFormRef" :inline="true" label-width="120px" class="mb20">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="独立运营组" prop="independentGroup">
            <el-input v-model="queryForm.independentGroup" placeholder="请输入独立运营组" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交易指令" prop="tradeOrder">
            <el-input v-model="queryForm.tradeOrder" placeholder="请输入交易指令" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否做空锁定" prop="shortRestrictFlag">
            <el-select v-model="queryForm.shortRestrictFlag" placeholder="请选择是否做空锁定" clearable style="width: 100%">
              <el-option label="未做空" :value="0" />
              <el-option label="做空" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-form :model="gridForm" :rules="rules" ref="gridFormRef" :inline="true" label-width="120px" class="mb20">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="公差" prop="commonDifference">
            <el-input v-model="gridForm.commonDifference" placeholder="请输入公差" />
          </el-form-item>
        </el-col>
        <!-- 添加变化趋势字段 -->
        <el-col :span="8">
          <el-form-item label="变化趋势" prop="trend">
            <el-select v-model="gridForm.trend" placeholder="请选择变化趋势" style="width: 100%">
              <el-option label="上升" :value="1" />
              <el-option label="振荡" :value="2" />
              <el-option label="下降" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 添加合约封顶价格字段 -->
        <el-col :span="8">
          <el-form-item label="合约封顶价格" prop="contractCapPrice">
            <el-input v-model="gridForm.contractCapPrice" placeholder="请输入合约封顶价格" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" @click="handleGenerateGrid">生成网格</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['trade:tradeBaseGrid:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['trade:tradeBaseGrid:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['trade:tradeBaseGrid:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['trade:tradeBaseGrid:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tradeBaseGridList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="唯一标识ID" align="center" prop="id" />-->
      <el-table-column label="节点价位" align="center" prop="gridNodePrice" sortable/>
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="实际成交价" align="center" prop="actualTradePrice" />
      <el-table-column label="网格成本价格" align="center" prop="gridPrice" />
      <el-table-column label="手续费" align="center" prop="fee" />
      <el-table-column label="是否已经做空锁定" align="center" prop="shortRestrictFlag">
        <template slot-scope="scope">
          <span v-if="scope.row.shortRestrictFlag === 1">做空</span>
          <span v-else-if="scope.row.shortRestrictFlag === 0">未做空</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="做空合约" align="center" prop="shortContract" />
      <el-table-column label="交易指令" align="center" prop="tradeOrder" />
      <el-table-column label="投资信息id" align="center" prop="investmentId" />
      <el-table-column label="投资人姓名" align="center" prop="investorName" />
      <el-table-column label="独立运营组" align="center" prop="independentGroup" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['trade:tradeBaseGrid:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['trade:tradeBaseGrid:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改交易基础网格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="节点价位" prop="gridNodePrice">
          <el-input v-model="form.gridNodePrice" placeholder="请输入节点价位" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="实际成交价" prop="actualTradePrice">
          <el-input v-model="form.actualTradePrice" placeholder="请输入实际成交价" />
        </el-form-item>
        <el-form-item label="网格价格" prop="gridPrice">
          <el-input v-model="form.gridPrice" placeholder="请输入网格价格" />
        </el-form-item>
        <el-form-item label="手续费" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入手续费" />
        </el-form-item>
        <el-form-item label="是否做空锁定" prop="shortRestrictFlag">
          <el-input v-model="form.shortRestrictFlag" placeholder="请输入是否做空锁定：0-未做空，1-做空" />
        </el-form-item>
        <el-form-item label="做空合约" prop="shortContract">
          <el-input v-model="form.shortContract" placeholder="请输入做空合约" />
        </el-form-item>
        <el-form-item label="交易指令" prop="tradeOrder">
          <el-input v-model="form.tradeOrder" placeholder="请输入交易指令" />
        </el-form-item>
        <el-form-item label="投资信息id" prop="investmentId">
          <el-input v-model="form.investmentId" placeholder="请输入投资信息id" />
        </el-form-item>
        <el-form-item label="投资人姓名" prop="investorName">
          <el-input v-model="form.investorName" placeholder="请输入投资人姓名" />
        </el-form-item>
        <el-form-item label="独立运营组" prop="independentGroup">
          <el-input v-model="form.independentGroup" placeholder="请输入独立运营组" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTradeBaseGrid, getTradeBaseGrid, delTradeBaseGrid, addTradeBaseGrid, updateTradeBaseGrid, generateGrid } from "@/api/trade/tradeBaseGrid"

export default {
  name: "TradeBaseGrid",
  data() {
    return {
      // 查询表单数据
      queryForm: {
        independentGroup: null,
        tradeOrder: null,
        shortRestrictFlag: null
      },
      // 新增网格表单数据
      gridForm: {
        quantity: null,
        cost: null,
        availableCashBalance: null,
        currentSecurityPrice: null,
        contractPrice: null,
        contractPositionStatus: '',
        contractQuantity: null,
        fee: null,
        optionType: null,
        range: null,
        commonDifference: null,
        // 添加新字段
        trend: null,
        contractCapPrice: null
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交易基础网格表格数据
      tradeBaseGridList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        gridNodePrice: null,
        independentGroup: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 新增生成网格方法
    handleGenerateGrid() {
      this.$refs.gridFormRef.validate(valid => {
        if (valid) {
          this.$modal.confirm('确认生成网格数据吗？').then(() => {
            generateGrid(this.gridForm).then(response => {
              this.$modal.msgSuccess("生成成功")
              this.getList() // 刷新表格数据
            }).catch(error => {
              // 处理后端抛出的异常
              if (error && error.message) {
                this.$modal.msgError(error.message)
              } else {
                this.$modal.msgError("生成网格数据失败")
              }
            })
          }).catch(() => {})
        }
      })
    },
    /** 查询交易基础网格列表 */
    getList() {
      this.loading = true
      listTradeBaseGrid(this.queryParams).then(response => {
        this.tradeBaseGridList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gridNodePrice: null,
        quantity: null,
        actualTradePrice: null,
        gridPrice: null,
        fee: null,
        shortRestrictFlag: null,
        shortContract: null,
        range: null,
        commonDifference: null,
        tradeOrder: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.independentGroup = this.queryForm.independentGroup
      this.queryParams.tradeOrder = this.queryForm.tradeOrder
      this.queryParams.shortRestrictFlag = this.queryForm.shortRestrictFlag
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryFormRef")
      this.queryForm = {
        independentGroup: null,
        tradeOrder: null,
        shortRestrictFlag: null
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加交易基础网格"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTradeBaseGrid(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改交易基础网格"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTradeBaseGrid(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTradeBaseGrid(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('ids:',this.ids)
      console.log('id:',row.id)

      // 单行删除
      if (row && row.id) {
        // 检查是否为做空锁定状态
        if (row.shortRestrictFlag === 1) {
          this.$modal.msgError("该数据已做空锁定，不允许删除！")
          return
        }

        const ids = row.id
        this.$modal.confirm('是否确认删除交易基础网格编号为"' + ids + '"的数据项？').then(function() {
          return delTradeBaseGrid(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      }
      // 批量删除
      else {
        if (this.ids.length === 0) {
          this.$modal.msgWarning("请选择要删除的数据")
          return
        }

        // 获取选中的行数据
        const selectedRows = this.tradeBaseGridList.filter(item => this.ids.includes(item.id))

        // 筛选出非做空锁定的数据
        const validRows = selectedRows.filter(item => item.shortRestrictFlag !== 1)
        const lockedRows = selectedRows.filter(item => item.shortRestrictFlag === 1)

        if (validRows.length === 0) {
          this.$modal.msgError("所选数据均为做空锁定状态，无法删除！")
          return
        }

        let confirmMessage = `是否确认删除选中的 ${validRows.length} 条数据项？`
        if (lockedRows.length > 0) {
          confirmMessage += `\n注意：${lockedRows.length} 条做空锁定数据将被跳过。`
        }

        this.$modal.confirm(confirmMessage).then(() => {
          const validIds = validRows.map(item => item.id)
          return delTradeBaseGrid(validIds)
        }).then(() => {
          this.getList()
          if (lockedRows.length > 0) {
            this.$modal.msgSuccess(`删除成功！已跳过 ${lockedRows.length} 条做空锁定数据。`)
          } else {
            this.$modal.msgSuccess("删除成功")
          }
        }).catch(() => {})
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('trade/tradeBaseGrid/export', {
        ...this.queryParams
      }, `tradeBaseGrid_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
